package com.example.demo.dao;

import com.example.demo.model.BorrowRecord;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 借阅记录数据访问层
 */
public class BorrowRecordDAO {
    private HikariDataSource dataSource;

    public BorrowRecordDAO(HikariDataSource dataSource) {
        this.dataSource = dataSource;
    }

    // 添加借阅记录
    public boolean addBorrowRecord(BorrowRecord record) {
        String sql = "INSERT INTO borrow_records(user_id, book_id, borrow_date, " +
                   "due_date, status, penalty) VALUES(?, ?, ?, ?, ?, ?)";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setLong(1, record.getUserId());
            pstmt.setLong(2, record.getBookId());
            pstmt.setDate(3, Date.valueOf(record.getBorrowDate()));
            pstmt.setDate(4, Date.valueOf(record.getDueDate()));
            pstmt.setString(5, record.getStatus().name());
            pstmt.setDouble(6, record.getPenalty());

            return pstmt.executeUpdate() > 0;

        } catch (SQLException e) {
            System.err.println("Error adding borrow record: " + e.getMessage());
            return false;
        }
    }

    // 根据ID查询借阅记录
    public BorrowRecord getBorrowRecordById(Long id) {
        String sql = "SELECT * FROM borrow_records WHERE id = ?";
        
        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setLong(1, id);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                BorrowRecord record = new BorrowRecord();
                record.setId(rs.getLong("id"));
                record.setUserId(rs.getLong("user_id"));
                record.setBookId(rs.getLong("book_id"));
                record.setBorrowDate(rs.getDate("borrow_date").toLocalDate());
                record.setDueDate(rs.getDate("due_date").toLocalDate());
                record.setReturnDate(rs.getDate("return_date") != null ? 
                    rs.getDate("return_date").toLocalDate() : null);
                record.setStatus(BorrowRecord.Status.valueOf(rs.getString("status")));
                record.setPenalty(rs.getDouble("penalty"));
                record.setRemarks(rs.getString("remarks"));
                return record;
            }

        } catch (SQLException e) {
            System.err.println("Error getting borrow record by ID: " + e.getMessage());
        }
        
        return null;
    }

    // 更新归还日期
    public boolean updateReturnDate(Long id, LocalDate returnDate) {
        String sql = "UPDATE borrow_records SET return_date = ? WHERE id = ?";
        
        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setDate(1, Date.valueOf(returnDate));
            pstmt.setLong(2, id);
            
            return pstmt.executeUpdate() > 0;

        } catch (SQLException e) {
            System.err.println("Error updating return date: " + e.getMessage());
            return false;
        }
    }

    // 更新罚金
    public boolean updatePenalty(Long id, double penalty) {
        String sql = "UPDATE borrow_records SET penalty = ? WHERE id = ?";
        
        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setDouble(1, penalty);
            pstmt.setLong(2, id);
            
            return pstmt.executeUpdate() > 0;

        } catch (SQLException e) {
            System.err.println("Error updating penalty: " + e.getMessage());
            return false;
        }
    }

    // 查询所有借阅记录
    public List<BorrowRecord> getAllBorrowRecords() {
        String sql = "SELECT * FROM borrow_records";
        List<BorrowRecord> records = new ArrayList<>();

        try (Connection conn = dataSource.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                BorrowRecord record = new BorrowRecord();
                record.setId(rs.getLong("id"));
                record.setUserId(rs.getLong("user_id"));
                record.setBookId(rs.getLong("book_id"));
                record.setBorrowDate(rs.getDate("borrow_date").toLocalDate());
                record.setDueDate(rs.getDate("due_date").toLocalDate());
                record.setReturnDate(rs.getDate("return_date") != null ? 
                    rs.getDate("return_date").toLocalDate() : null);
                record.setStatus(BorrowRecord.Status.valueOf(rs.getString("status")));
                record.setPenalty(rs.getDouble("penalty"));
                record.setRemarks(rs.getString("remarks"));
                records.add(record);
            }

        } catch (SQLException e) {
            System.err.println("Error getting all borrow records: " + e.getMessage());
        }
        
        return records;
    }
}